package com.motong.gongdan.util;

import org.apache.commons.jexl2.Expression;
import org.apache.commons.jexl2.JexlContext;
import org.apache.commons.jexl2.JexlEngine;
import org.apache.commons.jexl2.MapContext;

import java.util.HashMap;
import java.util.Map;

/**
 * @author:fff
 * @time:2022/5/17
 */
public class ExecuteStringAsCodeUtils {
    public Object executeString(String express, Map<String,Object> parameter) {
        JexlEngine jexlEngine = new JexlEngine();
        Expression expression = jexlEngine.createExpression(express);//将参数中的字符串传进来
        JexlContext jexlContext = new MapContext();
        if(parameter!=null && !parameter.isEmpty()){
            for(String key:parameter.keySet()) {//遍历传过来的参数
                jexlContext.set(key,parameter.get(key));//将传进来的参数替换到表达式中去
            }
        }
        if(null == expression.evaluate(jexlContext)) {//执行表达式
            return "";//为空就返回空字符串
        }
        return expression.evaluate(jexlContext);//执行表达式，返回结果
    }

    public static void main(String[] args) {
        ExecuteStringAsCodeUtils tool = new ExecuteStringAsCodeUtils();
        String condition = "1+2+3<=0";
//        int age = 1;
//        Map<String,Object> map=new HashMap<String,Object>();
//        map.put("age",age);
        boolean res = (boolean)tool.executeString(condition,null);
        System.out.println(res);


    }
}
